package com.wuwei.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.wuwei.pojo.CommonResult;
import com.wuwei.pojo.Payment;
import com.wuwei.service.FeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @description: CircleBreakerController <br>
 * @date: 2021/2/21 23:52 <br>
 * @author: wuwei666 <br>
 * @version: 1.0 <br>
 */
@RestController
@Slf4j
public class CircleBreakerController {

    @Value("${service.url.nacos-user-service}")
    private String SERVER_URL;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback",
            fallback = "handlerFallback",
            blockHandler = "handlerBlock",
            exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback(@PathVariable("id") Long id){
        CommonResult result = restTemplate.getForObject(SERVER_URL + "/provider/" + id, CommonResult.class);

        if (id.equals(4)){
            throw new IllegalArgumentException("非法参数异常");
        }else if(result.getData() == null){
            throw new NullPointerException("该ID没有对应记录，空指针异常");
        }
        return result;
    }
    public CommonResult<Payment> handlerFallback(@PathVariable("id") Long id,Throwable throwable){
        return new CommonResult<Payment>(4444, "代码内部出现异常handlerException" + throwable.getMessage(),null);
    }
    public CommonResult<Payment> handlerBlock(@PathVariable("id") Long id,Throwable throwable){
        return new CommonResult<Payment>(5555, "SentinelhandlerException" + throwable.getMessage(),null);
    }

    @Autowired
    private FeignService feignService;

    /*@GetMapping("/consumer/payment/{id}")
    public CommonResult<Payment> paymentCommonResult(@PathVariable("id") Long id){
        return paymentService.payment1(id);
    }*/
}
